package ca.cbc.msb.console.bean;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import ca.cbc.medialib.entity.Media;
import ca.cbc.msb.console.transaction.MediaTransaction;
import ca.cbc.msb.console.util.FacesMessageUtil;

@Controller
@Scope("session")
public class MediaBean implements Serializable {
	private static final long serialVersionUID = -4406972699026543176L;
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Inject
	private MediaTransaction mediaTransaction;
	private List<Media> items;
	private Media selected;
    
	private void sync() {
		items =  mediaTransaction.list();
	}
	
	public void update() {
		sync();
		FacesMessageUtil.instance.addMessage("Updated", "List has just been updated!");
	}
	
	@PostConstruct
	public void init() {
		logger.debug("^^^^^^^^^^^^^MediaBean PostConstruct!");
		sync();
	}
	
    public void delete(ActionEvent actionEvent) { 
    	if(mediaTransaction.remove(selected.getReleaseId())) {
    		FacesMessageUtil.instance.addMessage("Successful", 
    				"Media with title " + selected.getTitle() + " deleted!");
    	} else {
    		FacesMessageUtil.instance.addMessage("Warn", 
    				"Media with title " + selected.getTitle() + " already been deleted by msb!");
    	}
    	sync();
    	selected = null;
    }

    public void cancel(ActionEvent actionEvent) {
    	FacesMessageUtil.instance.addMessage("Canceled", "Delete canceled!");
    	selected = null;
    }
    
	public List<Media> getItems() {
		return items;
	}
	
	public Media getSelected() {
		return selected;
	}
	
	public void setSelected(Media selected) {
		logger.debug("Set Media ({}, {})", selected.getReleaseId(), selected.getTitle());
		this.selected = selected;
	}
}
